/*
 * author      : 吴中勤 
 * date        : 2018/11/11
 * description : TODO
 */

package org.wzq.learn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@RestController
public class ShopController {

    private static final Logger logger = LoggerFactory.getLogger(ShopController.class);

    @Value("${server.port}")
    private String port;

    @RequestMapping(value = {"/ruok"}, method = RequestMethod.GET)
    public String hello(@RequestParam(value = "name", defaultValue = "dormi") String name) {
        return "hi " + name + " ,i am from port:" + port;
    }

    // 测试在采样率 0.1的情况下，错误是否被正确采样s
    @RequestMapping(value = {"/wrong"}, method = RequestMethod.GET)
    public String wrong() {
        if (logger.isInfoEnabled()) logger.info("wrong 500");
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "wrong500");
    }

//    @Bean
//    public Sampler defaultSampler() {
//        return Sampler.ALWAYS_SAMPLE;
//    }


    @RequestMapping(value = {"/shops"}, method = RequestMethod.GET)
    public List<Shop> listShop() {
        return Shop.mockShops();
    }


    @RequestMapping(method = RequestMethod.POST, value = "/shops/{shopId}", consumes = "application/json")
    public Shop updateShop(@PathVariable("shopId") String shopId, @RequestBody Shop shop) {
        logger.info("updateShop, shopId={}, shop={}", shopId, shop);
        shop.setShopId(shopId);
        shop.setName("from port" + port);
        return shop;
    }


    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/service-instances/{applicationName}")
    public List<ServiceInstance> serviceInstancesByApplicationName(@PathVariable String applicationName) {
        return this.discoveryClient.getInstances(applicationName);
    }


}
